public class DeadLock {
    private static Object lock1=new Object();
    private static Object lock2=new Object();
    public static void main(String[] args) {
        Thread t1=new Thread(()-> {
            synchronized(lock1) {
                System.out.println("t1对lock1加锁完成");
                //这里的sleep是为了确保t1和t2都先分别拿到一把锁,然后尝试获取对方的锁,构成死锁
                //若没有sleep,执行顺序就不可控,可能出现某个线程一口气拿到两把锁,另一个线程一把都没有,从而无法构成死锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized(lock2) {   //注意获取第二把锁需要在第一把锁还没释放的情况下.
                    System.out.println("t1对lock2加锁完成");
                }
            }
        });
        Thread t2=new Thread(()-> {
            synchronized(lock1) {
                System.out.println("t2对lock1加锁完成");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized(lock2) {   //注意获取第二把锁需要在第一把锁还没释放的情况下.
                    System.out.println("t2对lock2加锁完成");
                }
            }
        });
        t1.start();
        t2.start();
    }
}
